package com.andnux.android.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.andnux.android.MainApp;
import com.andnux.android.adapter.OrdersCommentAdapter;
import com.andnux.android.adapter.PhotoAdapter;
import com.andnux.android.data.ChatSession;
import com.andnux.android.data.OrdersComment;
import com.andnux.android.data.PageData;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.data.Works;
import com.andnux.android.databinding.ActivityWorksDetailsBinding;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.GsonUtils;
import com.andnux.android.network.NotNullConsumer;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.andnux.android.network.SuccessConsumer;
import com.andnux.android.utils.DateUtils;
import com.andnux.android.utils.ImageLoader;
import com.andnux.android.utils.StringUtils;
import com.google.gson.reflect.TypeToken;

import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class WorksDetailsActivity extends BaseActivity<ActivityWorksDetailsBinding> {

    private DesignCloudApi api;
    private PhotoAdapter adapter;
    private OrdersCommentAdapter commentAdapter;
    private Works works;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        works = (Works) getIntent().getSerializableExtra("works");
        api = RetrofitClient.getInstance().getServerApi();
        adapter = new PhotoAdapter();
        commentAdapter = new OrdersCommentAdapter();
        binding.comments.setAdapter(commentAdapter);

        binding.images.setAdapter(adapter);
        SystemUsers users = MainApp.getApp().getSystemUsers();

        binding.userLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WorksDetailsActivity.this, UserWorksActivity.class);
                intent.putExtra("users", works.getUsers());
                startActivity(intent);
            }
        });
        binding.linearLayout.setVisibility(StringUtils.toString(users.getId()).contentEquals(works.getUserId())
                ? View.GONE : View.VISIBLE);

        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        binding.buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WorksDetailsActivity.this, BuyActivity.class);
                intent.putExtra("works", works);
                startActivity(intent);
            }
        });

        binding.chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chatSessionInsert();
            }
        });
        binding.commentsTitle.setVisibility(View.GONE);
        binding.comments.setVisibility(View.GONE);
        loadData();
        loadComment();
    }

    private void loadComment() {
        addDisposable(api.orderCommentPage(0, 10, works.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<PageData<List<OrdersComment>>>>() {
                    @Override
                    public void onSuccess(Result<PageData<List<OrdersComment>>> result) {
                        List<OrdersComment> list = result.getData().getList();
                        commentAdapter.setNewData(list);
                        binding.commentsTitle.setVisibility(list.size() > 0 ? View.VISIBLE : View.GONE);
                        binding.comments.setVisibility(list.size() > 0 ? View.VISIBLE : View.GONE);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        if (throwable != null) {
                            Toast.makeText(WorksDetailsActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }


    @Override
    protected void onDestroy() {
        adapter.stop();
        super.onDestroy();
    }

    private void doChat(ChatSession session) {
        Intent intent = new Intent(WorksDetailsActivity.this, ChatActivity.class);
        intent.putExtra("session", session);
        startActivity(intent);
    }

    private void chatSessionInsert() {
        ChatSession session = new ChatSession();
        session.setCreateTime(new Date());
        SystemUsers users = MainApp.getApp().getSystemUsers();
        session.setCreator(String.valueOf(users.getId()));
        session.setFromId(String.valueOf(users.getId()));
        session.setToId(works.getUserId());
        session.setWorksId(String.valueOf(works.getId()));
        session.setDeleted("0");
        session.setMessage(users.getNickname() + "发起了会话");
        session.setToBeReadMessCount(0);
        session.setWorks(works);
        session.setFromUser(users);
        session.setToUser(works.getUsers());
        addDisposable(api.chatSessionInsert(session)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SuccessConsumer<Result<String>>() {
                    @Override
                    public void onSuccess(Result<String> result) {
                        session.setSessionId(result.getData());
                        session.setWorks(works);
                        doChat(session);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (throwable != null) {
                            Toast.makeText(WorksDetailsActivity.this,
                                    throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }

    private void updateWorksViews() {
        addDisposable(api.worksViews(works.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<Works>>() {
                    @Override
                    public void onSuccess(Result<Works> result) {

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (throwable != null) {
                            Toast.makeText(WorksDetailsActivity.this,
                                    throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }

    private void loadData() {
        ImageLoader.load(works.getUsers().getAvatar(), binding.hedImage);
        Date updateTime = works.getUsers().getUpdateTime();
        if (updateTime == null) {
            updateTime = works.getCreateTime();
        }
        binding.title.setText(works.getUsers().getNickname());
        binding.time.setText(DateUtils.format(updateTime, DateUtils.DATE_PATTERN));
        binding.price.setText(StringUtils.toString(works.getPrice()));
        binding.worksTitle.setText(StringUtils.toString(works.getTitle()));
        binding.content.setText(StringUtils.toString(works.getContent()));
        binding.views.setText(StringUtils.toString(works.getViews(), "1") + "浏览");
        String json = works.getFiles();
        List<String> files = GsonUtils.gson.fromJson(json, new TypeToken<List<String>>() {
        }.getType());
        adapter.setNewData(files);
        updateWorksViews();
    }
}